﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MensUnoShop.Models;
using MensUnoShop.Filters;
using MensUnoShop.Models.ViewModels;
using MensUnoShop.Models.Discount;
using SenerPro;

namespace MensUnoShop.Controllers
{
    public class OrderController : Controller
    {
        //
        // GET: /Order/
        private Member _member;
        private List<Tag> _toptaglist;
        private string _title;

        public OrderController()
        {
            _member = MemberFactory.GetMember();
            _toptaglist = TagFactory.GetTopTagList();

        }

        public ActionResult fs(string id)
        {
            if (_member == null)
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "請先登入", URI = "/" });
            }
            else
            {
                ShoppingCart sc = ShoppingCart.GetShoppingCart();
                if (sc != null && sc.MLIST != null && sc.MLIST.Count() > 0)
                {
                    //將購物車key入DB
                    sc.SaveToDatabase(_member.MGUID);
                    //將購物車轉成訂單
                    Order od = OrderFactory.TransToOrder(sc, _member.MGUID);

                    //刪除購物車
                    sc.FreeCookie();
                    //轉到訂單流程

                    string scck = BlowFish.Encrypt(Tools.ToBase64URLString(Tools.BinarySerialize(od)), Config.key);
                    ViewData["scguid"] = id;
                    ViewData["scck"] = scck;
                    return View();
                }
            }
            return Redirect("/");
        }

        [HttpPost]
        public ActionResult f1(string id)
        {
            if (_member == null)
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "請先登入", URI = "/market/c" });
            }
            else
            {
                ShoppingCart sc = ShoppingCart.GetShoppingCart();
                if (sc != null && sc.MLIST != null && sc.MLIST.Count() > 0)
                {
                    //將購物車key入DB
                    sc.SaveToDatabase(_member.MGUID);
                    //將購物車轉成訂單
                    Order od = OrderFactory.TransToOrder(sc, _member.MGUID);

                    //刪除購物車
                    //sc.FreeCookie();
                    //轉到訂單流程

                    string scck = BlowFish.Encrypt(Tools.ToBase64URLString(Tools.BinarySerialize(od)), Config.key);
                    ViewData["scguid"] = id;
                    ViewData["scck"] = scck;
                    return View();
                }
            }
            return Redirect("/");
        }

        [MemberCheckFilter]
        public ActionResult f2(string id, string scck)
        {
            Guid scguid;
            bool isbirth = false;
            bool hasbirth = false;
            if (Guid.TryParse(id,out scguid) && !string.IsNullOrEmpty(scck))
            {
                //把order轉回來
                Order od = (Order)Tools.DeSerialize(Tools.FormBase64URLString(
                                                            BlowFish.Decrypt(scck, Config.key)));
                if (od.SCGUID == scguid)
                {                   
                    OrderViewModel nmv = new OrderViewModel()
                    {
                        MEMBER = _member,
                        OD = od,
                        SCCK = scck,
                        TOPLIST = _toptaglist
                    };
                    ViewData["IsBirth"] = isbirth;
                    ViewData["HasBirth"] = hasbirth;
                    return View(nmv);
                }
            }
            
            return Redirect("/");
        }

        [HttpPost]
        [MemberCheckFilter]
        public ActionResult f2(string utype, string shippingarea, string scck)
        {
            //把order轉回來
            Order od = (Order)Tools.DeSerialize(Tools.FormBase64URLString(
                                                        BlowFish.Decrypt(scck, Config.key)));
            _member.GetCoupon();
            bool isbirth = false;
            bool hasbirth = false;
            if (od != null)
            {
                #region 買千折百折扣
                od.DSKLIST.RemoveAll(d => d.SKTYPE == Config.OrderDiscountType.HanselDiscount);
                HandselDiscount hsd = new HandselDiscount(od);
                hsd.GetDiscount();
                if(hsd.DEPRICE>0)
                    od.DSKLIST.Add(hsd);
                #endregion

                if (utype == "selarea")
                {
                    od.SetDeliveryCost(shippingarea);
                    od.Cal();
                }

                if (!od.MLIST.Any(m => m.TYPE == Config.MarketType.Mangazine))
                {
                    BirthdayDiscount bd = (BirthdayDiscount)od.DSKLIST.SingleOrDefault(dsk => dsk.SKTYPE == Config.OrderDiscountType.BirthDiscount);
                    if (bd != null)
                    {
                        if (utype == "selbirth")
                        {
                            if (Request.Form["isbirth"] == "0")
                            {
                                od.DSKLIST.Remove(bd);
                                isbirth = false;
                                hasbirth = true;
                            }
                        }
                        else
                        {
                            isbirth = true;
                            hasbirth = true;
                        }
                    }
                    else
                    {
                        #region Birth折扣
                        bd = new BirthdayDiscount(DateTime.Parse(_member.BIRTH), _member.SIGNUP, od);
                        bd.GetDiscount();
                        if (bd.DEPRICE > 0)
                        {
                            if (utype == "selbirth")
                            {
                                if (Request.Form["isbirth"] == "1")
                                {
                                    od.DSKLIST.Add(bd);
                                    isbirth = true;
                                    hasbirth = true;

                                    //如果選擇生日折扣，就把優惠券取消
                                    if (od.MCID != 0)
                                    {
                                        od.DSKLIST.RemoveAll(d => d.SKTYPE == Config.OrderDiscountType.CouponDiscount);
                                        _member.COUPON.RemoveAll(c => c.MCID == od.MCID);
                                        _member.ResetCoupon(od.MCID);
                                    }
                                }
                            }
                            else if (utype != "selcoupona")
                            {
                                od.DSKLIST.Add(bd);
                                isbirth = true;
                                hasbirth = true;
                            }
                            else
                                hasbirth = true;
                        }
                        #endregion

                        if (utype == "selcoupona")
                        {
                            if (od.TOTALPRICE > 1000)
                            {
                                int mcid = 0;
                                if (_member.SetCoupon(Request.Form["ticket"], ref mcid))
                                {
                                    //ViewData["alert"] = "優惠券登錄成功!";
                                    od.MCID = mcid;
                                }
                                else
                                    ViewData["alert"] = "此序號錯誤或已使用過 Wrong or used code.";
                            }
                            else
                                ViewData["alert"] = "購物須滿NT$1000才可使用<br/> To use it, you have to purchase over NT$1,000 .";
                        }

                    }

                    #region Coupon折扣
                    od.DSKLIST.RemoveAll(d => d.SKTYPE == Config.OrderDiscountType.CouponDiscount);
                    var coupon = _member.COUPON.SingleOrDefault(c => c.MCID == od.MCID);
                    if (coupon != null)
                    {
                        CouponDiscount cfd = new CouponDiscount(coupon, od);
                        cfd.GetDiscount();
                        od.DSKLIST.Add(cfd);
                    }
                    #endregion
                }
                od.Cal();

                scck = BlowFish.Encrypt(Tools.ToBase64URLString(Tools.BinarySerialize(od)), Config.key);
                OrderViewModel nmv = new OrderViewModel()
                {
                    MEMBER = _member,
                    OD = od,
                    SCCK = scck,
                    TOPLIST = _toptaglist
                };
                ViewData["IsBirth"] = isbirth;
                ViewData["HasBirth"] = hasbirth;
                return View(nmv);
            }
            return Redirect("/");
        }

        [HttpPost]
        [MemberCheckFilter]
        public ActionResult f3(string id, string scck, string firstname, string lastname, string sex, string tel, string country, string zip, string city, string area, string address, string customer, byte ivtype, string ivtitle, string ivserial)
        {
            Guid scguid;
            if (Guid.TryParse(id, out scguid) && !string.IsNullOrEmpty(scck))
            {
                //把order轉回來
                Order od = (Order)Tools.DeSerialize(Tools.FormBase64URLString(
                                                            BlowFish.Decrypt(scck, Config.key)));
                if (od.SCGUID == scguid)
                {
                    Recipient rc = new Recipient(od.OGUID);
                    rc.ADDRESS = address;
                    rc.AREA = area;
                    rc.CITY = city;
                    rc.CUSTOMER = customer;
                    rc.TEL = tel;
                    rc.NAME = lastname + firstname;
                    rc.ZIP = zip;
                    rc.COUNTRY = country;
                    if (sex == "0")
                        rc.SEX = false;
                    else
                        rc.SEX = true;
                    od.RECIPIENT = rc;

                    //各種訂單折扣(要確認順序)
                    od.Cal();
                    od.INVOICETYPE = ivtype;
                    od.INVOICETITLE = ivtitle;
                    od.INVOICESERIAL = ivserial;
                    scck = BlowFish.Encrypt(Tools.ToBase64URLString(Tools.BinarySerialize(od)), Config.key);
                    OrderViewModel nmv = new OrderViewModel()
                    {
                        MEMBER = _member,
                        OD = od,
                        SCCK = scck,
                        TOPLIST = _toptaglist
                    };
                    return View(nmv);
                }
            }

            return Redirect("/");
        }

        [HttpPost]
        [MemberCheckFilter]
        public ActionResult pay(string id, string scck)
        {
            Guid scguid;
            if (Guid.TryParse(id, out scguid) && !string.IsNullOrEmpty(scck))
            {
                //把order轉回來
                Order od = (Order)Tools.DeSerialize(Tools.FormBase64URLString(
                                                            BlowFish.Decrypt(scck, Config.key)));
                if (od.SCGUID == scguid)
                {
                    try
                    {
                        OrderViewModel nmv = new OrderViewModel()
                        {
                            MEMBER = _member,
                            OD = od,
                            SCCK = scck,
                            TOPLIST = _toptaglist
                        };
                        return View(nmv);

                        }
                   catch (Exception ex)
                    {
                        Logger _log = new Logger(Config.logpath);
                        _log.RecordException(_log.FlowLogPath, "[pay]" + ex.ToString());
                        Session["failresponse"] = "交易不存在!!!";
                        Session["failordermarket"] = od.MLIST;
                        return RedirectToAction("of");
                    }
                }
            }

            return Redirect("/");
        }

        public string of()
        {
            //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("FDXDCYKPTGJL", "MD5").ToLower(); 
            return Session["failresponse"].ToString();
            
        }

        public ActionResult pay2(string id, string scck, int? payway)
        {
            Guid scguid;
            if (Guid.TryParse(id, out scguid) && !string.IsNullOrEmpty(scck))
            {
                //把order轉回來
                Order od = (Order)Tools.DeSerialize(Tools.FormBase64URLString(
                                                            BlowFish.Decrypt(scck, Config.key)));
                if (od.SCGUID == scguid)
                {
                    try
                    {
                        //驗證資料庫中有沒有紀錄
                        if (ShoppingCart.Check(od.SCGUID, _member.MGUID))
                        {
                            ShoppingCart sc = new ShoppingCart();
                            sc.FreeCookie();
                            //確認庫存都有被扣住
                            if (od.CheckStock())
                            {
                                //產生訂單編號
                                od.GetTxid();
                                od.TITLE += od.TXID;
                                od.DATEIN = DateTime.Now;
                                od.PW = (PayType)payway.Value;


                                #region//存入資料庫(訂單正式建立)
                                if (od.SaveToDatabase(true))
                                {
                                    //正式扣除
                                    for (int i = 0; i < od.DSKLIST.Count; i++)
                                    {
                                        if (od.DSKLIST[i].SetDiscount(od.TXID))
                                            od.SetDiscount(od.DSKLIST[i].SKTYPE, od.DSKLIST[i].DEPRICE, od.DSKLIST[i].TITLE);
                                        else
                                        {
                                            od.DSKLIST.RemoveAt(i);
                                            od.Cal();
                                        }
                                    }
                                    //再確認一次
                                    foreach (IOrderSalesKit sk in od.SKGIFTLIST)
                                    {
                                        sk.Judge(od);
                                    }

                                    #region 產生交易資料
                                    //產生交易員
                                    TradeAnget ta = new TradeAnget();
                                    //交易吧!!
                                    if (ta.DoTrade(_member, ref od))
                                    {
                                        //更新庫存狀態
                                        od.Commit();
                                        od.SaveToDatabase(false);
                                        od.SaveToTemp();
                                        od.SetStatus(Config.OrderStatusType.Waiting);
                                        //交易成功，更新會員資料
                                        _member.UptCookie();
                                        Response.Clear();
                                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                                        Response.Write(ta.REDIRECTURL);
                                        return View();
                                    }
                                    else
                                    {
                                        //有折扣的要復原
                                        foreach (var d in od.DSKLIST)
                                        {
                                            d.DealFail(od.TXID);
                                        }
                                        od.SetStatus(Config.OrderStatusType.Fail);
                                        od.SaveToDatabase(false);
                                        //釋放庫存
                                        od.FreeStock();
                                        //讓購物車清除用的cookie
                                        HttpCookie hc = new HttpCookie("ispay");
                                        hc.Value = "200";
                                        Response.Cookies.Add(hc);
                                        Session["failordermarket"] = od.MLIST;
                                        Session["failresponse"] = "交易失敗";
                                        return RedirectToAction("of");
                                    }
                                    #endregion
                                }
                                else
                                {
                                    //有折扣的要復原
                                    foreach (var d in od.DSKLIST)
                                    {
                                        d.DealFail(od.TXID);
                                    }
                                    od.SetStatus(Config.OrderStatusType.Fail);
                                    od.SaveToDatabase(false);
                                    //釋放庫存
                                    od.FreeStock();
                                    //讓購物車清除用的cookie
                                    HttpCookie hc = new HttpCookie("ispay");
                                    hc.Value = "200";
                                    Response.Cookies.Add(hc);
                                    Session["failordermarket"] = od.MLIST;
                                    Session["failresponse"] = "訂單資料有誤，請重新交易，謝謝。";
                                    return RedirectToAction("of");
                                }
                                #endregion
                            }
                            else
                            {
                                Session["failordermarket"] = od.MLIST;
                                Session["failresponse"] = "不好意思，庫存不足!!";
                                return RedirectToAction("of");
                            }
                        }
                        else
                        {
                            Session["failordermarket"] = od.MLIST;
                            Session["failresponse"] = "購物車不存在!!";
                            return RedirectToAction("of");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger _log = new Logger(Config.logpath);
                        _log.RecordException(_log.FlowLogPath, "[pay]" + ex.ToString());
                        Session["failresponse"] = "交易不存在!!!";
                        Session["failordermarket"] = od.MLIST;
                        return RedirectToAction("of");
                    }
                }
            }
            return Redirect("/");
        }
       
        [MemberCheckFilter]
        public ActionResult query()
        {
            List<SimpleOrder> odlist = OrderFactory.GetOrderList(_member.MGUID).OrderByDescending(o=>o.DATEIN).ToList();
                OrderViewModel nmv = new OrderViewModel()
                {
                    MEMBER = _member,
                    ODLIST = odlist,
                    TOPLIST = _toptaglist
                };
                return View(nmv);

        }

        [MemberCheckFilter]
        [HttpPost]
        public ActionResult query(string txid)
        {
            Order o = OrderFactory.GetOrderByTxid(txid);
            if (o != null)
            {
                if(o.STATUS==Config.OrderStatusType.Shipping)
                    o.SetStatus(Config.OrderStatusType.ApplyReturn);
            }
            return RedirectToAction("query");
        }

        [MemberCheckFilter]
        public ActionResult querydetail(string id)
        {
            Order od = OrderFactory.GetOrderByTxid(id);
            od.GetOrderMarketList();
            od.GetRecipient();
            od.GetSimpleDiscount();
            OrderViewModel nmv = new OrderViewModel()
            {
                MEMBER = _member,
                OD = od,
                TOPLIST = _toptaglist
            };
            return View(nmv);

        }
    }
}
